package com.software.levelupandroid.taskShow.model;

import android.content.Context;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.Task;
import com.software.levelupandroid.home.CallBack;
import com.software.levelupandroid.utils.OkhttpUtil;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * @Description 根据任务状态展示任务的Repository
 * @Author LiangYaJie
 * @CreateTime 2024年05月29日 11:32:45
 */
public class TaskShowRepository {
    private static TaskShowRepository taskShowRepository;
    private List<Task> tasks = new ArrayList<>();

    public static TaskShowRepository getTaskShowRepository(){
        if (taskShowRepository == null){
            taskShowRepository = new TaskShowRepository();
        }
        return taskShowRepository;
    }

    public void getAllTasksByStatus(CallBack<List<Task>> callBack, Context context, int status){
        Call call = OkhttpUtil.getRequest("task/getAllTasksByStatus?status=" + status, context);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                callBack.onFailure(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String resp = response.body().string();

                Result<List<Task>> result = convertJsonToTaskList(resp);

                if (result != null){
                    if (result.getCode() != null && result.getCode().equals("200")){
                        List<Task> tasks = result.getData();
                        callBack.onSuccess(tasks);
                    }else {
                        callBack.onFailure("result.getCode==null||result.getCode.equals('200'): 获取任务失败");
                    }
                }else {
                    callBack.onFailure("result==null: 未成功获取数据");
                }
            }
        });

    }

    /**
     * 将json转换为Result<List<Task>>类型
     * @param respJson
     * @return
     */
    public Result convertJsonToTaskList(String respJson){
        Gson gson = new Gson();
        Type type = new TypeToken<Result<List<Task>>>() {}.getType();
        Result<List<Task>> result = gson.fromJson(respJson, type);

        return result;
    }
}
